<?php

namespace app\stores\logic\order;

use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingIntegralModel;


class OrderCashLogic{

    use OrderTrait;

    protected $goods_data=[];

    protected $total_price=0;

    protected $member_coupon_id;

    protected $sku_datas=[];

    protected $order_item_data=[];

    protected $num;

    protected $all_goods_gross;

    public function createOrder($params)

    {
        //判断用户
        if($params['member_id'] && $params['member_id']>0){

            $this->checkMember($params['member_id'], false);

        }

        //判断商品
        if(empty($params['goods']) || !is_array($params))   $this->error('请选择商品');

        foreach ($params['goods'] as $k => $v){

            $this->checkGoods($v,false);

        }

        //if(empty($params['total_price'])) $this->error('参数错误1#');

        //if((float)$params['total_price'] != $this->total_price) $this->error('参数错误2#');

        //判断优惠卷

        $coupon_id = $params['coupon_id'] ?? 0;

        $couponBalance = 0;

        if(!empty($coupon_id)){

            if(null === $myCoupon =  MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');

            if($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用');

            if($myCoupon->member_id != $params['member_id'])  $this->error('该优惠券不可用');

            $couponBalance = $myCoupon->coupon_money;

        }


        //判断积分抵扣

        $use_integral=(int)$params['use_integral'];

        if($use_integral==1){

            $integral_balance=$this->getIntegralBalance($this->total_price);

        }

        $integral=isset($integral_balance) ? $integral_balance['integral'] : 0;

        $balance=isset($integral_balance) ? $integral_balance['balance'] : 0;


        //获取需要支付的金额

        $need_pay=round((($this->total_price)*100 - $couponBalance*100 - $balance*100)/100,2);


        //保存订单

        $order = new GoodsOrderModel();

        $order_data=[

            'shop_id'=>$this->shopId,

            'order_type'=>'cash',

            'member_id'=>$params['member_id'],

            'total_price'=>$this->total_price,

            'need_pay'=>$need_pay,

            'member_coupon_id'=>$params['coupon_id'],

            'coupon_money'=>$couponBalance,

            'use_integral'=>isset($integral_balance) ? $integral_balance['integral'] : 0,

            'integral_balance'=>isset($integral_balance) ? $integral_balance['balance'] : 0,

            'is_paid'=>0,

            'status'=>(isset($params['is_gua_order']) && $params['is_gua_order'])?16:1,

            'from_type'=>$params['from_type'],

            'all_goods_gross'=>$this->all_goods_gross,

            'add_time'=>time(),

            'add_ip'=>request()->ip(),

            'open_table_id'=>(isset($params['open_table_id']) && $params['open_table_id'])?implode(',',$params['open_table_id']):NULL,
        ];

        $order->order_id = $order->insertGetId($order_data);

        GoodsOrderModel::where(['order_id'=>$order->order_id])->save(['order_sn'=>createOrderSn($order->order_id,7)]);

        //保存订单商品
    
        foreach ($this->order_item_data as $k => $v){

            $this->order_item_data[$k]['order_id']=$order->order_id;

        }

        $order_item_model= new GoodsOrderItemModel();

        $order_item_model->saveAll($this->order_item_data);


        //保存商品

        $goods_model=new GoodsModel();

        $goods_model->saveAll($this->goods_data);



        //保存商品规格

        $goods_sku_model = new GoodsSkuModel();

        $goods_sku_model->saveAll($this->sku_datas);



        return $order->order_id;

    }


    public function checkGoods($datas,$lock)

    {

        empty($datas['goods_id']) && $this->error('参数错误#31');

        empty($datas['num']) && $this->error('参数错误#4');

        $this->num = ($this->num ?? 0) + $datas['num'];



        $goods=GoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['goods_id','=',$datas['goods_id']]

        ])->field('type,shop_id,category_id,goods_id,name,cover_img,original_price,crossed_price,vip_price,quota,gross,take_count,fictitious_take_count,is_have_sku,vip_discount_type,discount_detail')

            ->json(['discount_detail'],true)

            ->lock($lock)->find($datas['goods_id']);

        empty($goods) && $this->error('商品不存在');

        $goods->price = $goods->crossed_price;

        if($this->member){

            $return = getMemberPrice($this->member,$this->shopId,$goods,$goods['crossed_price'],$goods['type']);

            if($return){

                $goods->price = $return['price'];
            }
        }

        $sku_id=isset($datas['sku_id']) ? $datas['sku_id'] : 0;

        if($sku_id != 0){

            $sku=GoodsSkuModel::where([

                ['shop_id','=',$this->shopId],

                ['is_delete','=',0],

                ['goods_id','=',$datas['goods_id']],

                ['sku_id','=',$sku_id],

//                ['quota','>=',$datas['num']]

            ])->field('sku_id,name,original_price,crossed_price,vip_price,quota,take_count,discount_detail,gross')

                ->json(['discount_detail'],true)

                ->lock($lock)->find();

            if(null === $sku) $this->error($goods->name.'的规格缺货');

            $sku->price = $sku->crossed_price;

            $skus[] = $sku->toArray();

            if($this->member){

                $return = skuMemberPrice($goods->vip_discount_type,$skus,$this->member,$this->shopId,$goods['type'],2);

                if($return){

                    $sku->price = $return[0]['price'];
                }
            }

            $discount_detail = $sku->discount_detail;
        }else{

            $discount_detail = $goods->discount_detail;

        }
        $level_id = $this->member?getMemberLevel($this->member->member_id,$this->shopId):0;

        $discount = $this->member?getMemberDiscount($this->member,$this->shopId,$goods->vip_discount_type,$discount_detail):0;

        //单位
        $category = GoodsCategoryModel::where(['category_id'=>$goods['category_id'],'is_delete'=>0])->find();

        //处理订单商品表

        $cate_name = $category?$category->name:null;

        if($goods->type==3) $cate_name = '套餐';

        $this->order_item_data[]=[

            'shop_id'=>$this->shopId,

            'goods_id'=>$datas['goods_id'],

            'goods_type'=>'cash',

            'category_name'=>$cate_name,

            'goods_name'=>$goods->name,

            'goods_cover_img'=>$goods->cover_img,

            'goods_gross'=>isset($sku)?$sku->gross:$goods->gross,

            'goods_sku_id'=>$sku_id,

            'goods_sku_name'=>isset($sku) ? $sku->name : '',

            'goods_original_price'=>isset($sku) ? $sku->crossed_price : $goods->crossed_price,

            'goods_price'=>isset($sku) ? $sku->price : $goods->price,

            'goods_num'=>$datas['num'],

            'vip_discount_type'=>$level_id>0?$goods->vip_discount_type:0,

            'discount_detail'=>$level_id>0?$discount:0

        ];

        if(isset($sku)){

            $goods->sku = $sku;
        }

        $this->all_goods_gross += isset($sku)?$sku->gross * $datas['num']:$goods->gross * $datas['num'];

        if($this->member){

            $this->member->level_id = getMemberLevel($this->member->member_id,$this->shopId);
        }
        $price = isset($sku) ? (($this->member && $this->member->level_id ==0 )? $sku->crossed_price : $sku->price) : (($this->member && $this->member->level_id ==0 )? $goods->crossed_price : $goods->price);
       
        $this->total_price=round((($this->total_price)*100+$price*$datas['num']*100)/100,2);
        
        //处理商品表

        $goods=$goods->toArray();

        $goods['take_count']=$goods['take_count']+$datas['num'];

        $goods['fictitious_take_count']=$goods['fictitious_take_count']+$datas['num'];

        $this->goods_data[]=$goods;



        //处理规格表

        if(isset($sku)){

            $sku=$sku->toArray();

            $sku['take_count']=$sku['take_count']+$datas['num'];

            $this->sku_datas[]=$sku;

        }



    }

    public function getIntegralBalance($total_price)

    {

        $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->shopId]])->find();

        if(null === $SettingBalance){

            $integral_deduction_balance_limit_rate = 0;

        }else{

            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比

        }

        $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->shopId]])->find();

        if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额

            $integral_exchange_balance = 0;

        }else{

            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率

        }



        $pre_can_exchange_balance=round(($total_price*($integral_deduction_balance_limit_rate*100))/10000,2);

        $pre_can_exchange_integral=$integral_exchange_balance==0 ? 0 : round(($pre_can_exchange_balance*10000)/($integral_exchange_balance*100),0);

        $member_integral=$this->member->integral;

        if($member_integral>=$pre_can_exchange_integral){

            $return=[

                'integral'=>$pre_can_exchange_integral,

                'balance'=>$pre_can_exchange_balance

            ];

        }else{

            $return=[

                'integral'=>$member_integral,

                'balance'=>round(($member_integral*($integral_exchange_balance*100))/10000,2),

            ];

        }

        return $return;



    }




}